package security

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

const (
	signature = "c02ba0b582501608"
)

// AesEncrypt 加密
func AesEncrypt(password string) (cryptedPassword string, err error) {
	defer func() {
		if exception := recover(); exception != nil {
			cryptedPassword = ""
			err = fmt.Errorf("%v", exception)
		}
	}()
	originData := []byte(password)
	key := []byte(signature)
	block, err := aes.NewCipher(key)
	if err != nil {
		return
	}
	blockSize := block.BlockSize()
	originData = pkcs7Padding(originData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(originData))
	blockMode.CryptBlocks(crypted, originData)
	cryptedPassword = base64.StdEncoding.EncodeToString(crypted)
	return
}

// AesDecrypt 解密
func AesDecrypt(cryptedPassword string) (password string, err error) {
	defer func() {
		if exception := recover(); exception != nil {
			password = ""
			err = fmt.Errorf("%v", exception)
		}
	}()
	crypted, err := base64.StdEncoding.DecodeString(cryptedPassword)
	if err != nil {
		panic(err)
	}
	key := []byte(signature)
	block, err := aes.NewCipher(key)
	if err != nil {
		return
	}
	blockMode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	originData := pkcs7UnPadding(origData)
	password = string(originData)
	return
}

func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func pkcs7UnPadding(originData []byte) []byte {
	length := len(originData)
	unpadding := int(originData[length-1])
	return originData[:(length - unpadding)]
}
